package com.xmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xmall.bean.table.Topic;
import com.xmall.bean.table.TopicExample;
import com.xmall.bean.vo.TopicListVo;
import com.xmall.bean.vo.WxTopicDetailVo;
import com.xmall.bean.vo.WxTopicListVo;
import com.xmall.mapper.TopicMapper;
import com.xmall.service.WxTopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class WxTopicServiceImpl implements WxTopicService {
    @Autowired
    TopicMapper topicMapper;
    @Override
    public WxTopicDetailVo wxTopicDetail(Integer id) {
        TopicExample topicExample = new TopicExample();
        topicExample.createCriteria().andIdEqualTo(id);
        List<Topic> topics = topicMapper.selectByExample(topicExample);
        Topic topic = topics.get(0);

        WxTopicDetailVo wxTopicDetailVo = new WxTopicDetailVo();
        wxTopicDetailVo.setTopic(topic);
        wxTopicDetailVo.setGoods(topic.getGoods());
        return wxTopicDetailVo;
    }

    @Override
    public WxTopicListVo wxTopicList(Integer page, Integer size) {
        PageHelper.startPage(page, size);//设置分页

        TopicExample topicExample = new TopicExample();
        TopicExample.Criteria criteria = topicExample.createCriteria();
        criteria.andDeletedEqualTo(false);//查询数据库未逻辑删除的

        List<Topic> topics = topicMapper.selectByExample(topicExample);
        PageInfo<Topic> topicPageInfo = new PageInfo<>(topics);
        long total = topicPageInfo.getTotal();
        WxTopicListVo wxTopicListVo = new WxTopicListVo();
        wxTopicListVo.setCount((int) total);

        List<TopicListVo> data = new ArrayList<>();
        for (Topic topic : topics) {
            TopicListVo topicListVo = new TopicListVo();
            topicListVo.setId(topic.getId());
            topicListVo.setTitle(topic.getTitle());
            topicListVo.setSubtitle(topic.getSubtitle());

            topicListVo.setPrice(topic.getPrice());
            topicListVo.setReadCount(topic.getReadCount());
            topicListVo.setPicUrl(topic.getPicUrl());

            data.add(topicListVo);
        }
        wxTopicListVo.setData(data);

        return wxTopicListVo;


    }

    @Override
    public List<Topic> wxTopicRelated(Integer id) {
        PageHelper.startPage(0, 4);
        TopicExample topicExample = new TopicExample();
        //todo 排序规则？
        topicExample.setOrderByClause("read_count desc");
        TopicExample.Criteria criteria = topicExample.createCriteria();
        criteria.andIdNotEqualTo(id).andDeletedEqualTo(false);
        List<Topic> topics = topicMapper.selectByExample(topicExample);
        return topics;
    }
}
